package tt.Lematizador.Lexemas;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Lexema {
	String ArchGenerar;
	String ArchIndice;
	
	
	public Lexema(String ArchGenerar, String ArchIndice){
//		StringTokenizer token = new StringTokenizer(ArchGenerar,".");
	//	ArchIndice=token.nextToken();
		//ArchIndice=ArchIndice+"ArchIndice.txt";
		this.ArchGenerar=ArchGenerar;
		this.ArchIndice=ArchIndice;
	}
	
		
	public String getArchGenerar() {
		return ArchGenerar;
	}


	public void setArchGenerar(String archGenerar) {
		ArchGenerar = archGenerar;
	}

	public String getArchIndice() {
		return ArchIndice;
	}

	public void setArchIndice(String archIndice) {
		ArchIndice = archIndice;
	}

	private String Equivalente(String palabra,String lineaArchivo){
		String equivalente=null;
		String palabraArch=null;
		new StringTokenizer("");
		lineaArchivo = lineaArchivo.trim();
		if(!lineaArchivo.isEmpty()){
			StringTokenizer token2 = new StringTokenizer(lineaArchivo," ");
			StringTokenizer token3 = new StringTokenizer(token2.nextToken(),"-");
			palabraArch=token3.nextToken();
			
			while(token3.hasMoreTokens()){
				String a=token3.nextToken();
				if(!a.equals("@")) // se coloco como caso especial por que asi se encuentra la estructura del archivo, y es un caso que no interesa ***
					palabraArch=palabraArch+a;	
			}
			if(palabra.equals(palabraArch)){
				
				while(token2.hasMoreTokens()){
					equivalente=token2.nextToken();
				}
			}/**/
		}
		return equivalente;
	}
	
	public String getLexema(String palabra){
		
		//System.out.println("Ti "+System.currentTimeMillis() );
		palabra = palabra.trim();
		palabra = palabra.toLowerCase();
		String lexema=null;
		long indices[]=new long[2];
		boolean find=false;
		RandomAccessFile archIndices = null;
		//System.err.println("palabra = " + palabra);
		if(!palabra.isEmpty()){
			String lineaArchivo=null;
			indices=this.getIndiceLetra(palabra);
			try {
				archIndices = new RandomAccessFile(ArchGenerar,"r");
				archIndices.seek(indices[0]);
				//System.out.println(indices[0]);
				//System.out.println(indices[1]);
				if(indices[1]==-2){indices[1]=archIndices.length();}
				//System.err.println("LEXEMAS");
				//System.err.println("archIndices.getFilePointer() = " + archIndices.getFilePointer() + " < " + "archIndices.length()=" + archIndices.length());
				while (archIndices.getFilePointer() < indices[1] && find==false&&archIndices.getFilePointer()<archIndices.length()){
				//	System.err.println("archIndices.getFilePointer() = " + archIndices.getFilePointer() + " < " + "archIndices.length()=" + archIndices.length());
					lineaArchivo=archIndices.readLine();
					//System.out.println(lineaArchivo);
					//System.out.println(palabra);
					lexema=this.Equivalente(palabra, lineaArchivo);
					if (lexema!=null){
						find=true;
					}
				}
			} catch (FileNotFoundException e) {
//				System.out.println("Error al leer el archivo, Arhivo "+ this.ArchGenerar+" o " +this.ArchIndice + " no encontrado");
			} catch (IOException e) {
//				System.out.println("Error");
			} finally{
				try{
				archIndices.close();
				}catch(IOException e){
					e.printStackTrace();
				}
			}
		}
		//System.out.println("Tf "+System.currentTimeMillis() );
		return lexema;
	}
	
	
	
	private long[] getIndiceLetra(String palabra){
		long indices[]=new long[2];
		indices[0]=0; //[0] es el indice de inicio
		indices [1]=-1;// [1] es el indice final
		//String palabra2="";
		
		String lineaIndice=null;
		RandomAccessFile archIndices=null;
		boolean finAsignado=false;
		
		
		palabra=Omitir(palabra,"á","a");
		palabra=Omitir(palabra,"é","e");
		palabra=Omitir(palabra,"í","i");
		palabra=Omitir(palabra,"ó","o");
		palabra=Omitir(palabra,"ú","u");
		palabra=Omitir(palabra,"ü","u");
		
		//System.out.println(palabra);
		
		if(palabra.length()>2){
			//if(palabra.charAt(0) == 'a' || palabra.charAt(0) == 'c' || palabra.charAt(0) == 'd'
				//	|| palabra.charAt(0) == 'e' || palabra.charAt(0) == 'i'
					//|| palabra.charAt(0) == 'n' || palabra.charAt(0) == 'p'
					//|| palabra.charAt(0) == 'r' || palabra.charAt(0) == 's')
		       	//palabra=palabra.charAt(0)+""+palabra.charAt(1);
			//else
				//palabra=palabra.charAt(0) + "";
			palabra=palabra.charAt(0) + "" + palabra.charAt(1) + "" + palabra.charAt(2);
		}
		
		//System.out.println(palabra);
		
		
		try {
			archIndices = new RandomAccessFile(ArchIndice,"r");
			//System.err.println("LEXEMAS");
			//System.err.println("archIndices.getFilePointer() = " + archIndices.getFilePointer() + " < " + "archIndices.length()=" + archIndices.length());
			while (archIndices.getFilePointer() < archIndices.length() && finAsignado==false) {
				//System.err.println("archIndices.getFilePointer() = " + archIndices.getFilePointer() + " < " + "archIndices.length()=" + archIndices.length());
				lineaIndice=archIndices.readUTF();
				StringTokenizer token = new StringTokenizer(lineaIndice," ");
				lineaIndice=token.nextToken();
				//System.out.println(lineaIndice);
				//System.out.println(palabra);
				if(lineaIndice.equals(palabra)){
					indices[0] = new Long(Long.parseLong(token.nextToken()));
					//System.err.println("archIndices.getFilePointer() = " + archIndices.getFilePointer() + " < " + "archIndices.length()=" + archIndices.length());
					if(archIndices.getFilePointer() < archIndices.length()){
							//System.out.println("entre al if");
							lineaIndice=archIndices.readUTF();
							StringTokenizer tokenfin = new StringTokenizer(lineaIndice," ");
							tokenfin.nextToken();
							indices[1] = new Long(Long.parseLong(tokenfin.nextToken()));
				
                                                        finAsignado=true;
							//System.out.println(indices[0]);
					}
					else{
						indices[1] = -2;
						finAsignado=true;
					}
				}
			}
			
			
			//System.out.println(indices[0]+"  "+indices[1]);
		} catch (FileNotFoundException e) {
//			System.out.println("Error al leer el archivo, Arhivo "+ this.ArchGenerar+" o " +this.ArchIndice + " no encontrado");
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try{
			archIndices.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
		return indices;
	}
	
	
	public String Omitir (String pal,String x,String y)
	{
		StringBuffer sb = new StringBuffer();
		Pattern p = Pattern.compile(x);
        Matcher m = p.matcher(pal);
        
        boolean resultado = m.find();
        while(resultado) {
            m.appendReplacement(sb, y);
            resultado=m.find();
        }
        m.appendTail(sb);
        return sb.toString();
	}
}
